<?php
header("Access-Control-Allow-Origin: *");
ini_set("display_errors",1);
require 'Slim/Slim.php';

\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/getDetailProduct', 'getDetailProduct');
$app->get('/getMenuList', 'getMenuList');
$app->get('/getOnlineSupportList', 'getOnlineSupportList');
$app->get('/getAllProduct', 'getAllProduct');
$app->get('/admin/category', 'getCategoryAdmin');
$app->get('/admin/subCategory', 'getSubCategoryAdmin');
$app->get('/admin/subCategoryById', 'getSubCategoryById');
$app->get('/admin/product', 'getAllProduct');
$app->get('/admin/onlineSupport', 'getOnlineSupport');

$app->post('/admin/login', 'loginAdmin');
$app->post('/admin/category', 'addCategoryAdmin');
$app->post('/admin/subCategory', 'addSubCategory');
$app->post('/admin/product', 'addProduct');
$app->post('/upload', 'uploadImage');
$app->post('/admin/onlineSupport', 'addOnlineSupport');

$app->put('/admin/category', 'updateCategory');
$app->put('/admin/subCategory', 'updateSubCategory');
$app->put('/admin/password', 'updateUserPassword');
$app->put('/admin/onlineSupport', 'updateOnlineSupport');
$app->delete('/admin/category', 'deleteCategory');
$app->delete('/admin/subCategory', 'deleteSubCategory');
$app->delete('/admin/onlineSupport', 'deleteOnlineSupport');
$app->delete('/admin/product', 'deleteProduct');
$app->run();

function getDetailProduct(){
	global $app;
	$id = $app->request->params('id');
	getConnection();
	$sql="SELECT * 
		FROM product LEFT JOIN category ON product.cat_id = category.id 
			LEFT JOIN sub_category ON product.sub_id = sub_category.sub_id
		WHERE product_id = '$id'";
	$data = mysql_query($sql);
	closeConnection();
	$i=0;
	while($row = mysql_fetch_array($data)){
		$arr=array(
			"id"=>$row["product_id"],
			"name"=>$row["product_name"],
			"price"=>$row["price"],
			"description"=>$row["description"],
			"cat_id"=>$row["cat_id"],
			"cat_name"=>$row["name"],
			"sub_id"=>$row["sub_id"],
			"sub_name"=>$row["sub_name"],
			"image1"=> $row["image1"],
			"image2"=> $row["image2"],
			"image3"=> $row["image3"]
		);
	}
	echo '{	"data": '.json_encode($arr).'}';
}

function deleteProduct(){
	global $app;
	$id = $app->request->params('id');
	getConnection();
	$sql = "DELETE FROM product WHERE product_id = '$id'";
	mysql_query($sql);
	closeConnection();
}

function getOnlineSupportList(){
	$sql = "SELECT * FROM support";
	$arrData = array();
	getConnection();
	$result = mysql_query($sql);		
	$i=0;
	while($row = mysql_fetch_array($result)){
		$arrData[$i]=array(
			"id"=>$row["id"],
			"name"=>$row["name"],
			"mobile"=>$row["mobile"],
			"email"=>$row["email"]);
		$i++;
	}
	echo '{"data":'.json_encode($arrData).'}';
}

function deleteOnlineSupport(){
	global $app;
	$id = $app->request->params('id');
	getConnection();
	$sql = "DELETE FROM support WHERE id = '$id'";
	mysql_query($sql);
	closeConnection();
}

function updateOnlineSupport(){
	global $app;
    $app->response()->header("Content-Type", "application/json");
	$post = json_decode($app->request()->getBody());
	$postArray = get_object_vars($post);
	$name = $postArray["name"];
	$id = $postArray["id"];
	$type = $postArray["type"];
	getConnection();
		$sql="UPDATE support SET ";
		if($type == "name")
			$sql .= "name = '$name' ";
		else if($type == "mobile")
			$sql .= "mobile = '$name' ";
		else
			$sql .= "email = '$name' ";
		$sql .= "WHERE id = '$id'";
		$data = mysql_query($sql);
		closeConnection();
		echo '{"status": true,
				"msg": "Update thành công!"}';
	}

function getOnlineSupport(){
	global $app;
	$arr = array();
	getConnection();
	$sql="SELECT * FROM support";
	$data = mysql_query($sql);
	closeConnection();
	$i=0;
	while($row = mysql_fetch_array($data)){
		$arr[$i]=array(
			"id"=>$row["id"],
			"name"=>$row["name"],
			"mobile"=>$row["mobile"],
			"email"=>$row["email"]
		);
		$i++;
	}
	echo '{"data": '.json_encode($arr).'}';
}

function addOnlineSupport(){
	global $app;
    $app->response()->header("Content-Type", "application/json");
	$post = json_decode($app->request()->getBody());
	$postArray = get_object_vars($post);
	$name = $postArray["name"];
	$phone = $postArray["phone"];
	$mail = $postArray["mail"];
	getConnection();
	$sql="INSERT INTO support(name,mobile,email) VALUES('$name','$phone','$mail')";
	$data = mysql_query($sql);
	$id = mysql_insert_id();
	closeConnection();
	if($data){
		echo json_encode(array(
					'status'=>true,
					'msg'=> 'Thêm mới thành công!!!'
				));
	}else{
		echo json_encode(array(
					'status'=>false,
					'msg'=> 'error'
				));	
	}
}

function getAllProduct(){
	global $app;
	$limit = $app->request->params('limit');
	$page = $app->request->params('page');
	$begin = ($page-1)*$limit;
	
	$arr = array();
	$arr2 = array();
	getConnection();
	$sql="SELECT * FROM product ";
	$data = mysql_query($sql);
	$total = mysql_num_rows($data);
	$sql="SELECT * 
		FROM product LEFT JOIN category ON product.cat_id = category.id 
			LEFT JOIN sub_category ON product.sub_id = sub_category.sub_id
		ORDER BY product_id DESC LIMIT $begin, $limit ";
	$data = mysql_query($sql);
	closeConnection();
	$i=0;
	while($row = mysql_fetch_array($data)){
		$arr[$i]=array(
			"id"=>$row["product_id"],
			"name"=>$row["product_name"],
			"price"=>$row["price"],
			"description"=>$row["description"],
			"cat_id"=>$row["cat_id"],
			"cat_name"=>$row["name"],
			"sub_id"=>$row["sub_id"],
			"sub_name"=>$row["sub_name"],
			"image1"=> $row["image1"],
			"image2"=> $row["image2"],
			"image3"=> $row["image3"]
		);
		$i++;
	}
	echo '{	"data": '.json_encode($arr).',
			"total": '.$total.'}';
}

function addProduct(){
	global $app;
    $app->response()->header("Content-Type", "application/json");
	$post = json_decode($app->request()->getBody());
	$postArray = get_object_vars($post);
	$name = $postArray["name"];
	$catId= $postArray["catId"];
	$subId= !empty($postArray["subId"]) ? $postArray["subId"] : 0;
	$price= $postArray["price"];
	$desc= $postArray["desc"];
	$img1= !empty($postArray["image1"]) ? $postArray["image1"] : "";
	$img2= !empty($postArray["image2"]) ? $postArray["image2"] : "";
	$img3= !empty($postArray["image3"]) ? $postArray["image3"] : "";
	getConnection();
	$sql="INSERT INTO product(cat_id, sub_id, product_name, price, description, image1, image2, image3) VALUES('$catId','$subId','$name','$price','$desc','$img1','$img2','$img3')";
	$data = mysql_query($sql);
	$id = mysql_insert_id();
	closeConnection();
	if($data){
		echo json_encode(array(
					'status'=>true,
					'id'=> $id
				));
	}else{
		echo json_encode(array(
					'status'=>false,
					'msg'=> 'error'
				));	
	}
}
function updateUserPassword(){
	global $app;
    $app->response()->header("Content-Type", "application/json");
	$post = json_decode($app->request()->getBody());
	$postArray = get_object_vars($post);
	$name = $postArray["username"];
	$oldPw = $postArray["oldPassword"];
	$newPw = $postArray["newPassword"];
	getConnection();
	$sql0 = "SELECT * FROM users WHERE username = '$name' AND password='$oldPw'";
	$data0 = mysql_query($sql0);
	if(mysql_num_rows($data0)>0){
		$sql="UPDATE users SET password = '$newPw' WHERE username = '$name'";
		$data = mysql_query($sql);
		closeConnection();
		echo '{"status": true,
				"msg": "Update thành công!"}';
	}else{
		closeConnection();
		echo '{"status": false,
				"msg": "Thông tin tài khoản sai!"}';
	}
}

function updateSubCategory(){
	global $app;
    $app->response()->header("Content-Type", "application/json");
	$post = json_decode($app->request()->getBody());
	$postArray = get_object_vars($post);
	$name = $postArray["name"];
	$subId = $postArray["catSubId"];
	getConnection();
	$sql0 = "SELECT * FROM sub_category WHERE sub_name = '$name'";
	$data0 = mysql_query($sql0);
	if(mysql_num_rows($data0)>0){
		closeConnection();
		echo '{	"status": false,
				"msg":"Tên danh mục con trùng!"}';
	}else{
		$sql="UPDATE sub_category SET sub_name = '$name' WHERE sub_id=$subId ";
		$data = mysql_query($sql);
		closeConnection();
		echo '{"status": true,
				"msg": "Update thành công!"}';
	}
}

function deleteSubCategory(){
	global $app;
	$subId = $app->request->params('id');
	getConnection();
	$sql="DELETE FROM sub_category WHERE sub_id= $subId";
	$data = mysql_query($sql);
	closeConnection();
	
	echo '{"status": true }';
}

function addSubCategory(){
	global $app;
    $app->response()->header("Content-Type", "application/json");
	$post = json_decode($app->request()->getBody());
	$postArray = get_object_vars($post);
	$name = $postArray["name"];
	$catId= $postArray["catId"];
	
	getConnection();
	$sql0 = "SELECT * FROM sub_category WHERE sub_name = '$name' AND category_id=$catId";
	$data0 = mysql_query($sql0);
	if(mysql_num_rows($data0)>0){
		closeConnection();
		echo '{	"status": false,
				"msg":"Tên danh mục con trùng!"}';
	}else{
		$sql="INSERT INTO sub_category(category_id, sub_name) VALUES('$catId','$name')";
		$data = mysql_query($sql);
		closeConnection();
		echo '{"status": true,
				"msg": "Thêm thành công!"}';
	}
}

function deleteCategory(){
	global $app;
	$catId = $app->request->params('id');
	getConnection();
	$sql="DELETE FROM sub_category WHERE category_id= $catId";
	$data = mysql_query($sql);
	$sql="DELETE FROM category WHERE id=$catId";
	$data = mysql_query($sql);
	closeConnection();
	
	echo '{"status": true }';
}

function updateCategory(){
	global $app;
    $app->response()->header("Content-Type", "application/json");
	$post = json_decode($app->request()->getBody());
	$postArray = get_object_vars($post);
	$name = $postArray["name"];
	$catId = $postArray["catId"];
	getConnection();
	$sql0 = "SELECT * FROM category WHERE name = '$name'";
	$data0 = mysql_query($sql0);
	if(mysql_num_rows($data0)>0){
		closeConnection();
		echo '{	"status": false,
				"msg":"Tên danh mục trùng!"}';
	}else{
		$sql="UPDATE category SET name = '$name' WHERE id='$catId'";
		$data = mysql_query($sql);
		closeConnection();
		echo '{"status": true,
				"msg": "Update thành công!"}';
	}
}

function getMenuList() {
    $sql = "SELECT * FROM category LEFT JOIN sub_category ON category.id = sub_category.category_id";
	$arrData = array();
	getConnection();
	$result = mysql_query($sql);		
	$i=0;
	$j=0;
	while($row = mysql_fetch_array($result)){
		
		if($i==0){
			$arrData[$i]=array(
				"id"=>$row["id"],
				"name"=>$row["name"],
				"sub_menu"=>array()
			);
			if(!empty($row["sub_id"])){
				array_push($arrData[$i]["sub_menu"],array(
					"id"=>$row["sub_id"],
					"name"=>$row["sub_name"]
				));
			}			
		}else{
			if(!empty($row["sub_id"]) && $row["category_id"]==$arrData[$j]["id"]){
				array_push($arrData[$j]["sub_menu"],array(
					"id"=>$row["sub_id"],
					"name"=>$row["sub_name"]
				));
			}elseif(!empty($row["sub_id"]) && $row["category_id"]!=$arrData[$j]["id"]){
				$j++;
				$arrData[$j]=array(
					"id"=>$row["id"],
					"name"=>$row["name"],
					"sub_menu"=>array()
				);
				array_push($arrData[$j]["sub_menu"],array(
					"id"=>$row["sub_id"],
					"name"=>$row["sub_name"]
				));
				
			}elseif(empty($row["sub_id"])){
				$j++;
				$arrData[$j]=array(
					"id"=>$row["id"],
					"name"=>$row["name"],
					"sub_menu"=>array()
				);
				
			}
		}
		$i++;
	}
	closeConnection();
    echo '{"data":'.json_encode($arrData).'}';
}

function loginAdmin() {
	global $app;
    $app->response()->header("Content-Type", "application/json");
	$post = json_decode($app->request()->getBody());
	$postArray = get_object_vars($post);
	$username = $postArray["username"];
	$password = $postArray["password"];
	getConnection();
	$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."'";
	$result = mysql_query($sql);
	closeConnection();
	if(mysql_num_rows($result)>0){
		echo '{"token": "'.md5(uniqid()).'"}';
	} else{
		echo '{"error": "login fail"}';
	}
	
}

function getCategoryAdmin(){
	global $app;
	$limit = $app->request->params('limit');
	$page = $app->request->params('page');
	$begin = ($page-1)*$limit;
	
	$arr = array();
	getConnection();
	$sql="SELECT * FROM category ";
	$data = mysql_query($sql);
	$total = mysql_num_rows($data);
	$sql="SELECT * FROM category ORDER BY id DESC LIMIT $begin, $limit ";
	$data = mysql_query($sql);
	closeConnection();
	$i=0;
	while($row = mysql_fetch_array($data)){
		$arr[$i]=array(
			"id"=>$row["id"],
			"name"=>$row["name"]
		);
		$i++;
	}
	echo '{	"data": '.json_encode($arr).',
			"total": '.$total.'}';
}


function getSubCategoryAdmin(){
	global $app;
	$limit = $app->request->params('limit');
	$page = $app->request->params('page');
	$begin = ($page-1)*$limit;
	$arr = array();
	getConnection();
	$sql="SELECT * FROM sub_category as a, category as b WHERE a.category_id=b.id";
	$data = mysql_query($sql);
	$total = mysql_num_rows($data);
	$sql="SELECT * FROM sub_category as a, category as b WHERE a.category_id=b.id ORDER BY sub_id DESC LIMIT $begin, $limit ";
	$data = mysql_query($sql);
	closeConnection();
	$i=0;
	while($row = mysql_fetch_array($data)){
		$arr[$i]=array(
			"id"=>$row["sub_id"],
			"name"=>$row["sub_name"],
			"catId"=>$row["category_id"],
			"catName"=>$row["name"]
		);
		$i++;
	}
	echo '{"data": '.json_encode($arr).',
			"total": '.$total.'}';
}
function getSubCategoryById(){
	global $app;
	$id = $app->request->params('id');
	$arr = array();
	getConnection();
	
	$sql="SELECT * FROM sub_category WHERE category_id=$id ORDER BY sub_id DESC";
	$data = mysql_query($sql);
	closeConnection();
	$i=0;
	while($row = mysql_fetch_array($data)){
		$arr[$i]=array(
			"id"=>$row["sub_id"],
			"name"=>$row["sub_name"]
		);
		$i++;
	}
	echo '{"data": '.json_encode($arr).'}';
}
function addCategoryAdmin(){
	global $app;
    $app->response()->header("Content-Type", "application/json");
	
	$post = json_decode($app->request()->getBody());
	$postArray = get_object_vars($post);
	$name = $postArray["name"];
	
	getConnection();
	$sql0 = "SELECT * FROM category WHERE name = '$name'";
	$data0 = mysql_query($sql0);
	if(mysql_num_rows($data0)>0){
		closeConnection();
		echo '{	"status": false,
				"msg":"Tên danh mục trùng!"}';
	}else{
		$sql="INSERT INTO category(name) VALUES('$name')";
		$data = mysql_query($sql);
		closeConnection();
		echo '{"status": true,
				"msg": "Thêm thành công!"}';
	}
}



function uploadImage(){
	$allowedExts = array("gif", "jpeg", "jpg", "png");
	if(!empty($_FILES["file"]["name"])) $_FILES["file"]["name"] = trim($_FILES["file"]["name"]);
	$temp = explode(".", $_FILES["file"]["name"]);
	$extension = strtolower(end($temp));
	$name  = uniqid(32).".jpg";
	if ((($_FILES["file"]["type"] == "image/gif")
	|| ($_FILES["file"]["type"] == "image/jpeg")
	|| ($_FILES["file"]["type"] == "image/jpg")
	|| ($_FILES["file"]["type"] == "image/pjpeg")
	|| ($_FILES["file"]["type"] == "image/x-png")
	|| ($_FILES["file"]["type"] == "image/png"))
	&& ($_FILES["file"]["size"] < 40000000)
	&& in_array($extension, $allowedExts)) {
		if ($_FILES["file"]["error"] > 0) {
			
		} else {
			if (file_exists("../upload/$name" )) {
				echo json_encode(array(
					'status'=>false,
					'message'=> "$name  already exists."
				));
			}else{
				move_uploaded_file($_FILES["file"]["tmp_name"],"../upload/$name");
							
				echo json_encode(array(
					'status'=>true,
					'name'=>$name,
					'message'=> "Upload successfully"
				));
			}
			
		}
	} else {
		echo json_encode(array(
			'error'=>true,
			'message'=> "Invalid file",
			'file'=>$_FILES
		));
	}
	
}


function getConnection() {
	$con = mysql_connect("localhost","root","");
	mysql_select_db("msy",$con);
	//$con = mysql_connect("mysql.hostinger.vn","u251235146_v","xG9MfqxVRa");			
	//mysql_select_db("u251235146_android",$con);
	mysql_query('SET character_set_results=utf8');
	mysql_query('SET character_set_client=utf8');
	mysql_query('SET names=utf8');  
	
	mysql_query('SET character_set_connection=utf8');   			   
	mysql_query('SET collation_connection=utf8_unicode_ci'); 
	// return database handler
	return $con;
}

function closeConnection(){
	mysql_close();
}

?>